package com.example.questionsystem.modules.qu.service.impl;


import com.example.questionsystem.modules.qu.service.AnswerService;
import com.example.questionsystem.modules.qu.service.util.FileUtil;
import lombok.var;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

@Service
public class AnswerServiceImpl implements AnswerService {

    @Override
    public byte[] convertWordToExcel(MultipartFile file) throws IOException {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(file.getBytes());
             XWPFDocument doc = new XWPFDocument(bis)) {
            
            // 1. 提取文本内容
            String textContent = FileUtil.extractTextFromDocx(doc);
            
            // 2. 解析答案
            List<String> answers = parseAnswers(textContent);
            
            // 3. 生成Excel
            return createExcel(answers);
        }
    }

    private List<String> parseAnswers(String text) {
        List<String> answerList = new java.util.ArrayList<>();
        
        // 增强版正则表达式
        Pattern pattern = Pattern.compile(
            "(?:^|\\s|\\n)" +         // 开头或空白或换行
            "(\\d+)" +                // 题号
            "\\s*[.、:：]?\\s*" +      // 分隔符
            "([A-Za-z]{1,5})" +       // 答案
            "(?=\\s|\\n|$)"           // 结束标志
        );
        
        Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            String number = matcher.group(1);
            String answer = matcher.group(2).toUpperCase();
            answerList.add(number + "." + answer);
        }
        
        // 按题号排序
        answerList.sort(java.util.Comparator.comparingInt(s -> 
            Integer.parseInt(s.substring(0, s.indexOf('.')))
        ));
        
        return answerList;
    }

    private byte[] createExcel(List<String> answers) throws IOException {
        try (XSSFWorkbook workbook = new XSSFWorkbook();
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            
            var sheet = workbook.createSheet("答案");
            
            // 创建标题行
            var header = sheet.createRow(0);
            header.createCell(0).setCellValue("题号");
            header.createCell(1).setCellValue("答案");
            header.createCell(2).setCellValue("类型");
            
            // 填充数据
            for (int i = 0; i < answers.size(); i++) {
                var row = sheet.createRow(i + 1);
                String[] parts = answers.get(i).split("\\.", 2);
                
                row.createCell(0).setCellValue(parts[0]);
                if (parts.length > 1) {
                    row.createCell(1).setCellValue(parts[1]);
                    row.createCell(2).setCellValue(parts[1].length() > 1 ? "多选题" : "单选题");
                }
            }
            
            // 自动调整列宽
            for (int i = 0; i < 3; i++) {
                sheet.autoSizeColumn(i);
            }
            
            workbook.write(bos);
            return bos.toByteArray();
        }
    }
}